#include <event2/event.h>
#include <event2/buffer.h>
#include <event2/http.h>
#include <event2/http_struct.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

// /metrics 请求处理函数
void metrics_handler(struct evhttp_request *req, void *arg) {
    struct evbuffer *evb = evbuffer_new();
    if (!evb) return;

    // 随机生成示例数据
    int request_count = rand() % 1000;
    float temperature = 20.0f + (rand() % 1000) / 100.0f;

    // 输出 Prometheus 格式
 evbuffer_add_printf(evb, "# HELP myapp_status_total Total status by code\n");
 evbuffer_add_printf(evb, "# TYPE myapp_status_total counter\n");
 evbuffer_add_printf(evb, "myapp_status_total{code=\"200\"} %d\n", 200);
 evbuffer_add_printf(evb, "myapp_status_total{code=\"404\"} %d\n", 400);
 evbuffer_add_printf(evb, "myapp_status_total{code=\"500\"} %d\n", 500);

 evbuffer_add_printf(evb, "# HELP myapp_request_latency_seconds Request latency in seconds\n");
 evbuffer_add_printf(evb, "# TYPE myapp_request_latency_seconds gauge\n");
 evbuffer_add_printf(evb, "myapp_request_latency_seconds{method=\"GET\",endpoint=\"/api/v1/test\"} %.3f\n", 0.99);
 evbuffer_add_printf(evb, "myapp_request_latency_seconds{method=\"POST\",endpoint=\"/api/v1/login\"} %.3f\n", 0.44);
 evhttp_add_header(evhttp_request_get_output_headers(req), "Content-Type", "text/html");
    evhttp_send_reply(req, 200, "OK", evb);
    evbuffer_free(evb);
}

int main(int argc, char **argv) {
    struct event_base *base;
    struct evhttp *http;
    struct evhttp_bound_socket *handle;

    srand((unsigned)time(NULL));

    base = event_base_new();
    if (!base) {
        fprintf(stderr, "Couldn't create an event_base: exiting\n");
        return 1;
    }

    http = evhttp_new(base);
    if (!http) {
        fprintf(stderr, "Couldn't create evhttp: exiting\n");
        return 1;
    }

    // 绑定 /metrics 路径
    evhttp_set_cb(http, "/metrics", metrics_handler, NULL);

    // 监听 8000 端口
    handle = evhttp_bind_socket_with_handle(http, "0.0.0.0", 9913);
    if (!handle) {
        fprintf(stderr, "Couldn't bind to port 8000: exiting\n");
        return 1;
    }

    printf("Prometheus metrics server started at http://localhost:9913/metrics\n");
    event_base_dispatch(base);

    evhttp_free(http);
    event_base_free(base);
    return 0;
}
